﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using ScrumTable.Common;
using ScrumTable.Common.Collections;
using ScrumTable.Common.EventHandling;
using ScrumTable.Common.Threading;
using ScrumTable.DL.Data.Common;

#endregion


namespace ScrumTable.DL.Data.Generic
{
    /// <summary>
    /// This class encapsulates the base data access object service
    /// routines in order to access data from an external system.
    /// </summary>
    /// <remarks>The implementation of the data object class follows the Data Access Object pattern.</remarks>
    internal abstract class DataAccessObjectBase : DisposeBase, IDataAccessObject
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private readonly FastSmartWeakEvent<DataAccessObjectChangedEventHandler> _changedEvents = new FastSmartWeakEvent<DataAccessObjectChangedEventHandler>();
        private readonly GenericDataContextBase _context;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets the owning data layer context.
        /// </summary>
        internal GenericDataContextBase Context
        {
            get { return _context; }
        }

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new DataAccessObjectBase instance, no public constructor
        /// needed.
        /// </summary>
        internal DataAccessObjectBase(GenericDataContextBase context)
        {
            PreCondition.AssertNotNull(context, "context");

            _context = context;
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new IDataObject below the given parent id chain.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <returns>Returns the created object.</returns>
        public abstract IDataObject Insert(ValueChain<string> parentIdChain);

        /// <summary>
        /// Deletes the corresponding item from the data storage.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <param name="toDelete">Value which should be deleted.</param>
        public bool Delete(ValueChain<string> parentIdChain, IDataObject toDelete)
        {
            // not needed, elements cannot be deleted (yet)
            return false;
        }

        /// <summary>
        /// Deletes all items from the data storage with the given parent id.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        public void Delete(ValueChain<string> parentIdChain)
        {
            // not needed, elements cannot be deleted (yet)
        }

        /// <summary>
        /// Deletes all items from the data storage.
        /// </summary>
        public void Clear()
        {
            // not needed, elements cannot be deleted (yet)
        }

        /// <summary>
        /// Moves a IDataObject using the given id into a new parent object.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <param name="toMove">Specifies the data object to move inside the data storage.</param>
        /// <param name="newParentIdChain">Specifies the new parent id chain.</param>
        public abstract void Update(ValueChain<string> parentIdChain, IDataObject toMove, ValueChain<string> newParentIdChain);

        /// <summary>
        /// Updates the corresponding item in the data storage.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <param name="toUpdate">Value which should be updated.</param>
        public void Update(ValueChain<string> parentIdChain, IDataObject toUpdate)
        {
            // not needed, the storage is local
        }

        /// <summary>
        /// Retrieves all data objects which are stored in conjunction
        /// with the specified arguments.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <returns>Returns the retrieved data objects.</returns>
        public abstract ICollection<IDataObject> GetAll(ValueChain<string> parentIdChain);

        /// <summary>
        /// Retrieves all data objects which are stored in conjunction
        /// with the specified arguments.
        /// The data is retuned as callback and will be evaluated asynchronously but the callback will be fired in the main message loop.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <param name="callback">Specifies the asynchronous callback method. The callback value is of type DataResult&gt;ICollection&gt;IDataObject&lt;&lt;.</param>
        public void GetAll(ValueChain<string> parentIdChain, AsyncCallback callback)
        {
            PreCondition.AssertNotNull(parentIdChain, "parentIdChain");
            PreCondition.AssertNotNull(callback, "callback");

            callback(new DataResult<ICollection<IDataObject>>(GetAll(parentIdChain)));
        }

        /// <summary>
        /// Retrieves all data objects which are stored in the current dao.
        /// The structure of the given data objects is defined as follows:
        /// <example>
        /// <code>
        ///  [Parent Id Chain 1] -> Child Instance 1
        ///                      -> Child Instance 2
        ///                      -> Child Instance n
        /// 
        ///  [Parent Id Chain 2] -> Child Instance 3
        ///                      -> Child Instance 4
        ///                      -> Child Instance x
        /// </code>
        /// </example>
        /// </summary>
        /// <returns>Returns the retrieved data objects.</returns>
        public abstract IEnumerable<KeyValuePair<ValueChain<string>, ICollection<IDataObject>>> GetAll();

        /// <summary>
        /// Gets a single data object by its unqiue id.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <param name="id">Id of the data object.</param>
        /// <returns>Returns the retieved element or a null pointer, if it could not be found.</returns>
        public abstract IDataObject GetById(ValueChain<string> parentIdChain, string id);

        /// <summary>
        /// Gets a single data object by its unqiue id.
        /// The data is retuned as callback and will be evaluated asynchronously but the callback will be fired in the main message loop.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <param name="id">Id of the data object.</param>
        /// <param name="callback">Specifies the asynchronous callback method. The callback value is of type DataResult&gt;IDataObject&lt;.</param>
        public void GetById(ValueChain<string> parentIdChain, string id, AsyncCallback callback)
        {
            PreCondition.AssertNotNull(callback, "callback");

            callback(new DataResult<IDataObject>(GetById(parentIdChain, id)));
        }

        /// <summary>
        /// Enters a section which accommodates data access information.
        /// </summary>
        /// <remarks>
        /// This method must be used in conjunction with the using()
        /// statement.
        /// </remarks>
        protected DataAccessSection EnterDataAccessSection()
        {
            DataAccessSection dataAccessSection = null;

            try
            {
                dataAccessSection = new DataAccessSection(_context, null);
            }
            catch
            {
                if (dataAccessSection != null)
                {
                    dataAccessSection.Dispose();
                }
                throw;
            }
            return dataAccessSection;
        }

        /// <summary>
        /// Fills the elements of a given parent chain level into the
        /// given dictionary.
        /// </summary>
        /// <param name="all">Specifies the dictionary to fill.</param>
        /// <param name="parentIds">Specifies the unique parent key identifieres.</param>
        protected void FillLevel(IDictionary<ValueChain<string>, ICollection<IDataObject>> all, params string[] parentIds)
        {
            ValueChain<string> parentChain = new ValueChain<string>(parentIds);
            ICollection<IDataObject> elements = GetAll(parentChain);

            if (elements.Count > 0)
            {
                all[parentChain] = elements;
            }
        }

        /// <summary>
        /// Enters a critical section which must be used to access
        /// elements from the cache context.
        /// </summary>
        /// <remarks>
        /// This method must be used in conjunction with the using()
        /// statement.
        /// </remarks>
        /// <param name="parentValueChain">Specifies the parent key chain which is used to connect to the WSS / RS services.</param>
        /// <returns>Returns the lock exit condition.</returns>
        protected DataAccessSection EnterDataAccessSection(ValueChain<string> parentValueChain)
        {
            DataAccessSection dataAccessSection = null;

            try
            {
                dataAccessSection = new DataAccessSection(_context, parentValueChain);
            }
            catch
            {
                if (dataAccessSection != null)
                {
                    dataAccessSection.Dispose();
                }
                throw;
            }
            return dataAccessSection;
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        /// <summary>
        /// Occurs when the content of the data access object changes.
        /// </summary>
        public event DataAccessObjectChangedEventHandler DataAccessObjectChanged
        {
            add { _changedEvents.Add(value); }
            remove { _changedEvents.Remove(value); }
        }

        /// <summary>
        /// Fires the DataAccessObjectChanged event.
        /// </summary>
        /// <param name="args">Arguments to pass to the event receiver.</param>
        protected void OnDataAccessObjectChanged(DataAccessObjectChangedEventArgs args)
        {
            _changedEvents.Raise(this, args);
        }


        #region Lifecycle Procedures

        /// <summary>
        /// Retrieves a call after the connection to the back-end system has
        /// been established.
        /// </summary>
        internal virtual void OnConnected()
        {
        }

        /// <summary>
        /// Retrieves a call after the connection to the back-end system has
        /// been closed.
        /// </summary>
        internal virtual void OnDisconnected()
        {
        }

        /// <summary>
        /// Retrieves a call after the initial data of the back-end system has
        /// been loaded.
        /// </summary>
        internal virtual void OnInitialized()
        {
        }

        #endregion

        #endregion
    }
}